package com.jamal2362.apktool.fragment;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.jamal2362.apktool.MainActivity;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.fragment.editor.EditorPagerAdapter;
import com.jamal2362.apktool.fragment.editor.EditorTitleAdapter;
import com.jamal2362.apktool.fragment.files.ErrorTree;
import com.jamal2362.apktool.menu.Menus;
import com.jamal2362.apktool.util.MUtil;
import com.jamal2362.apktool.util.PopupUtils;
import com.jamal2362.apktool.util.Settings;
import com.jamal2362.apktool.util.TextUtil;
import com.jamal2362.apktool.util.search.SearchHistory;
import com.jamal2362.apktool.view.Editor;
import com.jamal2362.apktool.view.EditorPager;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EditorFragment extends Fragment implements Editor.OnEditStateChangedListener,ViewPager.OnPageChangeListener,OnClickListener, MenuItemCompat.OnActionExpandListener {
	private EditorPager editorPager;
	public EditorTitleAdapter open_files;
	private TextView empty, title;
	private LinearLayout quickPanelWrapper;
	private LinearLayout quickPanel;
	private MenuItem expandedItem = null;
	private View errors;
	private Map<Integer, File> arrFiles;
	private ImageView menuExpand;
	private View searchLayout;

	public void setRoot(ErrorTree errors) {
		EditorPagerAdapter.INSTANCE.setRoot(errors);
		errors.setEditor(this);
	}

	public void init() {
		EditorPagerAdapter.INSTANCE.setFragment(this);
		if (EditorPagerAdapter.INSTANCE.getCount() == 0) {
			empty.setVisibility(View.VISIBLE);
			quickPanelWrapper.setVisibility(View.GONE);
			menuExpand.setVisibility(View.GONE);
			closeSearch();
			((MainActivity)getActivity()).showFiles(0);
			if (title != null) {
				title.setText(R.string.app_name);
			}
		} else {
			empty.setVisibility(View.GONE);
			menuExpand.setVisibility(View.VISIBLE);
			if (Settings.quickPanel) {
				quickPanelWrapper.setVisibility(View.VISIBLE);
			}
		}
		((MainActivity)getActivity()).invalidateOptionsMenu();
		// initQuickPanel(((AppCompatActivity)getActivity()));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.editor_pager, container, false);
	}

	public void setEditable(boolean editable) {
		EditorPagerAdapter.INSTANCE.setEditable(editable);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		editorPager = view.findViewById(R.id.editorPager);
		empty = view.findViewById(R.id.empty);
		quickPanelWrapper = view.findViewById(R.id.quickPanelWrapper);
		quickPanel = quickPanelWrapper.findViewById(R.id.quickPanel);
		searchLayout = initSearchLayout(((AppCompatActivity)getActivity()), view);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
		AppCompatActivity act = (AppCompatActivity)getActivity();
		arrFiles = new HashMap<Integer, File>();
		open_files = new EditorTitleAdapter(this, editorPager);
		androidx.appcompat.app.ActionBar bar = act.getSupportActionBar();
		View customView = bar.getCustomView();
		title = customView.findViewById(R.id.name);
		EditorPagerAdapter.INSTANCE.bindContext(act, this);
		errors = customView.findViewById(R.id.errors);
		menuExpand = customView.findViewById(R.id.menu_expand);
		if (Settings.lightTheme)
			menuExpand.setImageResource(R.drawable.ic_collapse);
		else
			menuExpand.setImageResource(R.drawable.ic_collapse_dark);
		menuExpand.setOnClickListener(this);
		title.setText(R.string.app_name);
		title.setOnClickListener(this);
		editorPager.addOnPageChangeListener(this);
		editorPager.setAdapter(EditorPagerAdapter.INSTANCE);
		errors.setOnClickListener(this);
		init(savedInstanceState);
	}

	public void showErrors(boolean show) {
		errors.setVisibility(show ? View.VISIBLE : View.GONE);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.editor, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onPageScrolled(int p1, float p2, int p3) {
		// TODO: Implement this method
	}

	public void focus() {
		EditorPagerAdapter.INSTANCE.requestFocus(editorPager.getCurrentItem());
	}

	@Override
	public void onPageSelected(int idx) {
		EditorPagerAdapter.INSTANCE.requestFocus(idx);
		title.setText(EditorPagerAdapter.INSTANCE.getPageTitle(idx));
		menuExpand.setVisibility(View.VISIBLE);
		((AppCompatActivity)getActivity()).invalidateOptionsMenu();
	}

	@Override
	public void onPageScrollStateChanged(int p1) {
		// TODO: Implement this method
	}

	private void init(Bundle savedInstanceState) {
		int currentItem = 0;
		if (savedInstanceState != null) {
			currentItem = savedInstanceState.getInt("CURRENT_ITEM", 0);
		}
		if (EditorPagerAdapter.INSTANCE.getCount() == 0) {
			empty.setVisibility(View.VISIBLE);
			quickPanelWrapper.setVisibility(View.GONE);
		} else {
			empty.setVisibility(View.GONE);
			if (Settings.quickPanel) {
				quickPanelWrapper.setVisibility(View.VISIBLE);
			}
			editorPager.setCurrentItem(currentItem);
			onPageSelected(currentItem);
		}
		new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					initQuickPanel(((AppCompatActivity)getActivity()));
				}
			}, 100);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("CURRENT_ITEM", editorPager.getCurrentItem());
	}

	public void open(File file, final int start, final int stop) {
		open(Uri.fromFile(file), file);
		editorPager.postDelayed(new Runnable(){
				@Override
				public void run() {
					EditorPagerAdapter.INSTANCE.setSelection(editorPager.getCurrentItem(), start, stop);
				}
			}, 200);
	}

	public void open(Uri data, File file) {
		ContentResolver r = ((AppCompatActivity)getActivity()).getContentResolver();
		int idx = EditorPagerAdapter.INSTANCE.open(r, data);
		setCurrentItem(idx, false);
		empty.setVisibility(View.GONE);
		if (Settings.quickPanel) {
			quickPanelWrapper.setVisibility(View.VISIBLE);
		}
		((MainActivity)getActivity()).dismissFiles();
		if (file != null) {
			arrFiles.put(idx, file);
		}
	}

	public void open(File file) {
		open(Uri.fromFile(file), file);
	}

	public void setCurrentItem(int idx, boolean close) {
		if (close && idx == editorPager.getCurrentItem()) {
			close(idx);
			return;
		}
		editorPager.setCurrentItem(idx);
		onPageSelected(idx);
	}

	private void close(final int idx) {
		PopupUtils.show(title, R.menu.close_file, new PopupUtils.Callback(){
				@Override
				public void call(Context ctx, int pos) {
					int mode;
					switch (pos) {
						case R.id.close_cur:
							mode = 0;
							break;

						case R.id.close_others:
							mode = 1;
							break;

						case R.id.close_all:
							mode = 2;
							break;

						default:
							return;
					}
					close(idx, mode);
				}
			});
	}

	protected void close(int idx, int mode) {
		EditorPagerAdapter.INSTANCE.remove(idx, mode);
		if (EditorPagerAdapter.INSTANCE.getCount() == 0) {
			title.setText(R.string.app_name);
			empty.setVisibility(View.VISIBLE);
			quickPanelWrapper.setVisibility(View.GONE);
			menuExpand.setVisibility(View.GONE);
			((AppCompatActivity)getActivity()).invalidateOptionsMenu();
		} else {
			onPageSelected(editorPager.getCurrentItem());
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.name:
			case R.id.menu_expand:
				if (EditorPagerAdapter.INSTANCE.getCount() == 0)
					return;
				PopupUtils.show(title, EditorPagerAdapter.INSTANCE, new PopupUtils.Callback(){
						@Override
						public void call(Context ctx, int id) {
							setCurrentItem(id, true);
						}
					});
				break;

			case R.id.errors:
				((MainActivity)getActivity()).showFiles(2);
				break;
		}
	}

	public void save(boolean all, boolean toast) {
		if (all)
			EditorPagerAdapter.INSTANCE.saveAll();
		else
			EditorPagerAdapter.INSTANCE.save(editorPager.getCurrentItem());
		if (toast)
			TextUtil.st(((AppCompatActivity)getActivity()), getString(R.string.all_files_saved));
	}

	@Override
	public void onEditStateChanged() {
		onPageSelected(editorPager.getCurrentItem());
	}

	public boolean hasUnSavedEditor() {
		return EditorPagerAdapter.INSTANCE.hasUnSavedEditor();
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		int id;
		if (EditorPagerAdapter.INSTANCE.getCount() == 0)
			id = -1;
		else
			id = editorPager.getCurrentItem();
		Menus.prepare(menu, id);
		// menu.findItem(R.id.find).setOnActionExpandListener(this);
		MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.go_to_line), this);
		EditorPagerAdapter.INSTANCE.prepare(editorPager.getCurrentItem(), menu.findItem(R.id.translate));
	}

	@Override
	public boolean onMenuItemActionExpand(MenuItem p1) {
		expandedItem = p1;
		int idx = editorPager.getCurrentItem();
		if (p1.getItemId() == R.id.go_to_line)
			EditorPagerAdapter.INSTANCE.go_to(idx, (SearchView) MenuItemCompat.getActionView(p1));
		return true;
	}

	public boolean collapseItem() {
		if (expandedItem == null)
			return false;
		MenuItemCompat.collapseActionView(expandedItem);
		return true;
	}

	@Override
	public boolean onMenuItemActionCollapse(MenuItem p1) {
		expandedItem = null;
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		EditText set = searchLayout.findViewById(R.id.editorpagerEditText1);
		switch (item.getItemId()) {
			case R.id.save:
				save(false, true);
				break;

			case R.id.edit_mode:
				if (EditorPagerAdapter.INSTANCE.isEditable(editorPager.getCurrentItem())) {
					item.setTitle(R.string.edit_mode);
					setEditable(false);
					quickPanelWrapper.setVisibility(View.GONE);
				} else {
					item.setTitle(R.string.scan_mode);
					setEditable(true);
					if (Settings.quickPanel) {
						quickPanelWrapper.setVisibility(View.VISIBLE);
					}
				}
				break;

			case R.id.translate:
				EditorPagerAdapter.INSTANCE.translate(editorPager.getCurrentItem(), item);
				((AppCompatActivity)getActivity()).invalidateOptionsMenu();
				break;

			case R.id.find:
				if (!isSearchOpen()) {
					searchLayout.setVisibility(LinearLayout.VISIBLE);
					set.requestFocus();
					set.selectAll();
				} else {
					closeSearch();
				}
				break;

				/* Search Popup */
			case R.id.search_regexp:
				Settings.setb(((AppCompatActivity)getActivity()), "search_editor_regexp", !item.isChecked());
				set.requestFocus();
				set.selectAll();
				break;

			case R.id.search_case_sens:
				Settings.setb(((AppCompatActivity)getActivity()), "search_editor_csens", !item.isChecked());
				set.requestFocus();
				set.selectAll();
				break;

			case R.id.search_close:
				closeSearch();
				break;

			default:
				Menus.click(item, editorPager.getCurrentItem());
				break;
		}
		return true;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					initQuickPanel(((AppCompatActivity)getActivity()));
				}
			}, 100);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (EditorPagerAdapter.INSTANCE.getCount() == 0 || !Settings.quickPanel) {
			quickPanelWrapper.setVisibility(View.GONE);
		} else {
			quickPanelWrapper.setVisibility(View.VISIBLE);
		}
	}

	public boolean isSearchOpen() {
		return searchLayout.getVisibility() == LinearLayout.VISIBLE;
	}

	public boolean closeSearch() {
		if (isSearchOpen()) {
			searchLayout.findViewById(R.id.editorpagerLinearLayout2).setVisibility(LinearLayout.GONE);
			searchLayout.findViewById(R.id.editorpagerButton4).setEnabled(false);
			searchLayout.setVisibility(LinearLayout.GONE);
			focus();
			return true;
		}
		return false;
	}

	public void initQuickPanel(Context context) {
		quickPanel.removeAllViews();
		if (!Settings.quickPanel) {
			return;
		}
		final String[] chars = {"⇥", "/", "\\", ";", ":", "{", "}", "(", ")", "[", "]", "<", ">", "=", "\"", "'", "^", "+", "-", "_", "*", ",", ".", "|", "&", "!", "?"};
		DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    
		float dpPadding = 5.0f;
		int minHeight = (int) (Settings.fontSize + 10 + dpPadding * 2);
		int minWidth = Math.max((int) (displayMetrics.widthPixels / displayMetrics.density / (chars.length - 1)), minHeight);
		int buttonWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, minWidth, displayMetrics);
		int buttonHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, minHeight, displayMetrics);
		int paddingPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpPadding, getResources().getDisplayMetrics());
		LayoutParams param = new LayoutParams(
			LayoutParams.WRAP_CONTENT,      
			LayoutParams.WRAP_CONTENT
		);
		param.weight = 1.0f;
		param.width = buttonWidth;
		param.height = buttonHeight;
		for (final String ch : chars) {
			SpannableString spanString = new SpannableString(ch);
			spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
			Button charButton = new Button(context);
			charButton.setText(spanString);
			charButton.setTypeface(Settings.typeface);
			charButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, Settings.fontSize + 2);
			charButton.setBackgroundColor(Color.TRANSPARENT);
			charButton.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);
			charButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View p1) {
						String text = ch;
						if (text.equals("⇥")) {
							text = "    ";
						}
						if (isSearchOpen()) {
							EditText sedit = searchLayout.findViewById(R.id.editorpagerEditText1);
							EditText redit = searchLayout.findViewById(R.id.editorpagerEditText2);
							if (sedit.isFocused()) {
								insertText(sedit, text);
								return;
							}
							if (redit.isFocused()) {
								insertText(redit, text);
								return;
							}
						}
						EditorPagerAdapter.INSTANCE.printChars(editorPager.getCurrentItem(), text);
					}
				});
			quickPanel.addView(charButton, param);
		}
		int background = (Settings.lightTheme ? Color.WHITE : Color.DKGRAY);
		quickPanelWrapper.setBackgroundColor(background);
	}

	public View initSearchLayout(final Context context, View view) {
		int background = (Settings.lightTheme ? Color.WHITE : Color.DKGRAY);
		final LinearLayout searchLayout = view.findViewById(R.id.editorpagerLinearLayout1);
		searchLayout.setBackgroundColor(background);
		final ImageView searchHistoryButton = searchLayout.findViewById(R.id.editorpagerImageView1);
		if (Settings.lightTheme)
			searchHistoryButton.setImageResource(R.drawable.ic_collapse);
		else
			searchHistoryButton.setImageResource(R.drawable.ic_collapse_dark);
		final ImageView replaceHistoryButton = searchLayout.findViewById(R.id.editorpagerImageView2);
		if (Settings.lightTheme)
			replaceHistoryButton.setImageResource(R.drawable.ic_collapse);
		else
			replaceHistoryButton.setImageResource(R.drawable.ic_collapse_dark);
		ImageView searchMenu = searchLayout.findViewById(R.id.editorpagerImageView3);
		if (Settings.lightTheme)
			searchMenu.setImageResource(R.drawable.ic_dotsmenu);
		else
			searchMenu.setImageResource(R.drawable.ic_dotsmenu_dark);
		searchMenu.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View p1) {
					PopupMenu menu = new PopupMenu(context, p1);
					menu.inflate(R.menu.search);
					menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
							@Override
							public boolean onMenuItemClick(MenuItem item) {
								return onOptionsItemSelected(item);
							}
						});
					menu.getMenu().findItem(R.id.search_regexp).setChecked(Settings.getb(context, "search_editor_regexp", false));
					menu.getMenu().findItem(R.id.search_case_sens).setChecked(Settings.getb(context, "search_editor_csens", false));
					menu.show();
				}
			});
		final EditText search = searchLayout.findViewById(R.id.editorpagerEditText1);
		final EditText replace = searchLayout.findViewById(R.id.editorpagerEditText2);
		final SearchHistory searchHistory =new SearchHistory(context, "editor_search");
		final SearchHistory replaceHistory =new SearchHistory(context, "editor_replace");
		List<String> searchList = searchHistory.getHistory();
		List<String> replaceList = replaceHistory.getHistory();
		if (searchList.isEmpty()) {
			searchHistoryButton.setVisibility(View.GONE);
		} else {
			search.setText(searchList.get(searchList.size() - 1));
		}
		if (replaceList.isEmpty()) {
			replaceHistoryButton.setVisibility(View.GONE);
		} else {
			replace.setText(replaceList.get(replaceList.size() - 1));
		}
		searchHistoryButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View p1) {
					List<String> searchList = searchHistory.getHistory();
					PopupMenu menu = new PopupMenu(context, p1);
					int mid = 1500;
					for (int i = searchList.size(); i > 0; i--) {
						final String hitem = searchList.get(i - 1);
						MenuItem mitem = menu.getMenu().add(0, mid + i, 0, hitem);
						mitem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
							{
								@Override
								public boolean onMenuItemClick(MenuItem m) {
									search.setText(hitem);
									return true;
								}
							});
					}
					menu.show();
				}
			});
		searchHistoryButton.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View p1) {
					Runnable clear = new Runnable() {
						@Override
						public void run() {
							searchHistory.clear();
							searchHistoryButton.setVisibility(View.GONE);
						}
					};
					MUtil.createDialog(context, context.getString(R.string.clear_history), clear);
					return true;
				}
			});

		replaceHistoryButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View p1) {
					List<String> replaceList = replaceHistory.getHistory();
					PopupMenu menu = new PopupMenu(context, p1);
					int mid = 1600;
					for (int i = replaceList.size(); i > 0; i--) {
						final String hitem = replaceList.get(i - 1);
						MenuItem mitem = menu.getMenu().add(0, mid + i, 0, hitem);
						mitem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
							{
								@Override
								public boolean onMenuItemClick(MenuItem m) {
									replace.setText(hitem);
									return true;
								}
							});
					}
					menu.show();
				}
			});
		replaceHistoryButton.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View p1) {
					Runnable clear = new Runnable() {
						@Override
						public void run() {
							replaceHistory.clear();
							replaceHistoryButton.setVisibility(View.GONE);
						}
					};
					MUtil.createDialog(context, context.getString(R.string.clear_history), clear);
					return true;
				}
			});

		Button prevFind = searchLayout.findViewById(R.id.editorpagerButton1);
		Button nextFind = searchLayout.findViewById(R.id.editorpagerButton2);
		Button replaceButton = searchLayout.findViewById(R.id.editorpagerButton3);
		final Button replaceAllButton = searchLayout.findViewById(R.id.editorpagerButton4);
		replaceAllButton.setEnabled(false);
		OnClickListener buttonsClick = new OnClickListener() {
			@Override
			public void onClick(View p1) {
				final String searchStr = search.getText().toString();
				final String replaceStr = replace.getText().toString();
				if (TextUtils.isEmpty(searchStr) && p1.getId() != R.id.editorpagerButton3) {
					return;
				}
				searchHistory.putHistory(searchStr);
				searchHistoryButton.setVisibility(View.VISIBLE);
				switch (p1.getId()) {
					case R.id.editorpagerButton1:
						searchText(searchStr, false);
						break;

					case R.id.editorpagerButton2:
						EditorPagerAdapter.INSTANCE.find(editorPager.getCurrentItem(), searchStr, true);
						// searchText(searchStr, true);
						break;

					case R.id.editorpagerButton3:
						LinearLayout replaceLayout = searchLayout.findViewById(R.id.editorpagerLinearLayout2);
						if (replaceLayout.getVisibility() == LinearLayout.GONE) {
							replaceLayout.setVisibility(LinearLayout.VISIBLE);
							replaceAllButton.setEnabled(true);
						} else {
							if (TextUtils.isEmpty(searchStr)) {
								return;
							}
							replaceHistory.putHistory(replaceStr);
							replaceHistoryButton.setVisibility(View.VISIBLE);
							replaceText(searchStr, replaceStr, false);
						}
						break;

					case R.id.editorpagerButton4:
//						if (TextUtils.isEmpty(replaceStr)) {
//							return;
//						}
						replaceHistory.putHistory(replaceStr);
						replaceHistoryButton.setVisibility(View.VISIBLE);
						replaceText(searchStr, replaceStr, true);
						break;
				}
			}
		};
		prevFind.setOnClickListener(buttonsClick);
		nextFind.setOnClickListener(buttonsClick);
		replaceButton.setOnClickListener(buttonsClick);
		replaceAllButton.setOnClickListener(buttonsClick);
		return searchLayout;
	}

	private void searchText(String text, boolean next) {
		TextUtil.st(((AppCompatActivity)getActivity()), "Search " + (next ? "next" : "prev") + " «" + text + "»");
	}

	private void replaceText(String text, String replace, boolean replaceAll) {
		TextUtil.st(((AppCompatActivity)getActivity()), "Replace " + (replaceAll ? "all" : "one") + " match «" + text + "» to «" + replace + "»");
	}

	public void insertText(EditText edit, String text) {
		int start = Math.max(edit.getSelectionStart(), 0);
		int end = Math.max(edit.getSelectionEnd(), 0);
		edit.getText().replace(Math.min(start, end), Math.max(start, end), text, 0, text.length());
	}
}
